{% extends 'base.html' %}

{% block title %}游戏创建器{% endblock %}

{% block styles %}
<link rel="stylesheet" href="{{ url_for('static', filename='game_creator.css') }}">
{% endblock %}

{% block content %}
<div class="gc_container">
    <!-- 左侧栏：游戏列表 -->

    <!-- 中间：创建新游戏 -->
    <div class="gc_main-content">
        <h2>New Game</h2>
        <form id="createGameForm" action="{{ url_for('game_creator') }}" method="POST" enctype="multipart/form-data">
            <div class="gc_form-group">
                <label for="description">Description:</label>
                <textarea id="description" name="description" rows="2" placeholder="Optional: Enter game description"></textarea>
            </div>
            <div class="gc_form-group">
                <label for="words">Words:</label>
                <textarea id="words" name="words" rows="30" placeholder="Enter words here, one per line. e.g.
                
apple
banana
orange" required></textarea>
            </div>
            <div class="gc_form-group">
                <button type="submit" class="gc_btn" id="createGameBtn">Create Game</button>
            </div>
        </form>
        
        <!-- 将进度条替换为等待条 -->
        <div id="loadingContainer" style="display: none;">
            <div class="loading-spinner"></div>
            <p id="loadingText">Creating game...</p>
            <div id="progressContainer">
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <div class="progress-text">0%</div>
            </div>
        </div>

        <!-- Add success message and game link (initially hidden) -->
        <div id="successMessage" style="display: none;">
            <p>Game created successfully!</p>
            <p>Spell Game: <a id="spellGameLink" href="#" target="_blank"></a></p>
            <p>Translation Game: <a id="meaningGameLink" href="#" target="_blank"></a></p>
        </div>
    </div>

    <!-- 右侧栏：显示游戏的单词及其中文意思 -->

</div>

<script>
let totalSteps = 0;
let currentStep = 0;

function startProgressMonitoring() {
    // 重置进度
    currentStep = 0;
    // 计算总步骤数：单词数 × 每个单词的步骤数(3)
    const wordCount = document.getElementById('words').value.split('\n').filter(word => word.trim()).length;
    totalSteps = wordCount * 3;
    
    eventSource = new EventSource("{{ url_for('game_creation_progress') }}");
    
    eventSource.onmessage = function(event) {
        const data = JSON.parse(event.data);
        if (data.type === 'progress') {
            updateProgressBar(data);
        } else if (data.type === 'complete') {
            closeProgressMonitoring();
        }
    };

    eventSource.onerror = function(event) {
        console.error('SSE Error:', event);
        closeProgressMonitoring();
    };
}

function updateProgressBar(data) {
    currentStep++;
    const progressPercentage = Math.min((currentStep / totalSteps) * 100, 100);
    
    // 更新进度条
    const progressFill = document.querySelector('.progress-fill');
    const progressText = document.querySelector('.progress-text');
    
    progressFill.style.width = `${progressPercentage}%`;
    progressText.textContent = `${Math.round(progressPercentage)}%`;
    
    // 更新加载文本
    document.getElementById('loadingText').textContent = 
        `Creating game... (${currentStep}/${totalSteps} steps)`;
}

document.getElementById('createGameForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    // 重置进度条
    const progressFill = document.querySelector('.progress-fill');
    const progressText = document.querySelector('.progress-text');
    progressFill.style.width = '0%';
    progressText.textContent = '0%';
    
    // 开始监控进度
    startProgressMonitoring();
    
    var formData = new FormData(this);
    var xhr = new XMLHttpRequest();
    
    // 显示等待条
    document.getElementById('loadingContainer').style.display = 'block';
    document.getElementById('createGameBtn').disabled = true;

    xhr.onload = function() {
        if (xhr.status === 200) {
            var response = JSON.parse(xhr.responseText);
            if (response.success) {
                // 隐藏等待条并显示成功消息
                document.getElementById('loadingContainer').style.display = 'none';
                document.getElementById('successMessage').style.display = 'block';
                
                // 设置并显示拼写游戏链接
                var spellGameLink = '{{ url_for("game_spell", _external=True) }}?game_id=' + response.game_id;
                var spellGameLinkElement = document.getElementById('spellGameLink');
                spellGameLinkElement.href = spellGameLink;
                spellGameLinkElement.textContent = spellGameLink;

                // 设置并显示翻译游戏链接
                var meaningGameLink = '{{ url_for("game_translate", _external=True) }}?game_id=' + response.game_id;
                var meaningGameLinkElement = document.getElementById('meaningGameLink');
                meaningGameLinkElement.href = meaningGameLink;
                meaningGameLinkElement.textContent = meaningGameLink;
            } else {
                alert('Error creating game: ' + response.message);
            }
        } else {
            alert('Error creating game. Please try again.');
        }
        document.getElementById('createGameBtn').disabled = false;
    };

    xhr.open('POST', this.action, true);
    xhr.send(formData);
});

// 在成功创建游戏后关闭 SSE 连接
function closeProgressMonitoring() {
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
}
</script>

{% endblock %}
